package com.xyh.flowershop.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.xyh.flowershop.cache.RedisCache;
import com.xyh.flowershop.constant.CacheConstant;
import com.xyh.flowershop.constant.CommonConstant;
import com.xyh.flowershop.domain.User;
import com.xyh.flowershop.enums.RoleEnum;
import com.xyh.flowershop.exceptions.custom.BizException;
import com.xyh.flowershop.service.RegisterService;
import com.xyh.flowershop.service.UserService;
import com.xyh.flowershop.utils.CommonUtils;
import com.xyh.flowershop.vo.req.user.RegisterUserReqVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 小约翰可汗
 * @className RegisterServiceImpl
 * @createTime 2024/7/1414:21
 */
@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {

    private final RedisCache redisCache;

    private final UserService userService;

    public RegisterServiceImpl(RedisCache redisCache, UserService userService) {
        this.redisCache = redisCache;
        this.userService = userService;
    }

    @Override
    public void verifyCode(String email) {
        String code = CommonUtils.generateCode();
        log.info(email + "验证码为：" + code);
        redisCache.setCacheObject(CacheConstant.LOGIN_VERIFY_CODE_PREFIX + email, code, 10, TimeUnit.MINUTES);
        // TODO 发送验证码到邮箱
    }

    @Override
    public Boolean register(RegisterUserReqVo vo) {
        if(userService.checkUserIsExist(vo.getAccount())){
            throw new BizException("该账号已被注册，请重试");
        }
        String password =MD5.create().digestHex(vo.getPassword());
        User user = new User();
        user.setUserName(CommonUtils.randomUser());
        user.setPassword(password);
        user.setRole(RoleEnum.USER.getCode());
        user.setAccount(vo.getAccount());
        user.setCreateTime(new Date());
        return userService.save(user);
    }

}
